import * as dd from 'dingtalk-jsapi'
import {http} from '../http'

export class DingTalk {
  // dd.ready
  static ready() {
    return new Promise(resolve => {
      dd.ready(() => {
        resolve()
      })
    })
  }
  
  // 钉钉 JSAPI 鉴权
  static getJsApiTicket() {
    let params = {
      corpId: process.env.REACT_APP_DINGDING_CORPID,
      url: window.location.href
    }
    const jsApiList = [ // 必填，需要使用的jsapi列表，注意：不要带dd。
      'runtime.info',
      'device.notification.prompt',
      'biz.chat.pickConversation',
      'device.notification.confirm',
      'device.notification.alert',
      'device.notification.prompt',
      'biz.chat.open',
      'biz.util.open',
      'biz.user.get',
      'biz.contact.choose',
      'biz.telephone.call',
      'biz.util.uploadImage',
      'biz.ding.post',
    ]
    http('sign', {url: params.url}, {}).then(res => {
      let config = {
        agentId: res.agentId,
        corpId: res.corpId,
        timeStamp: res.timestamp,
        nonceStr: res.nonceStr,
        signature: res.signature,
        jsApiList: jsApiList
      }
      dd.config(config)
      dd.error(function (err) {
        alert('dd error: ' + JSON.stringify(err));
      })//该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题
    }).catch(err => {
      console.log(err)
    })
  }
  
  // 获取 authCode
  static async requestAuthCode(corpId) {
    return new Promise(async (resolve, reject) => {
      await DingTalk.ready()
      dd.runtime.permission.requestAuthCode({
        corpId,
        onSuccess: res => {
          resolve(res.code)
        },
        onFail: err => {
          console.log('error: ' + JSON.stringify(err))
        }
      })
    })
  }
  
  
  //单次获取经纬度
  static async getGeolocation() {
    return new Promise(async (resolve, reject) => {
      await DingTalk.getJsApiTicket()
      await DingTalk.ready()
      dd.device.geolocation.get({
        targetAccuracy: 200,
        coordinate: 1,
        withReGeocode: true,
        useCache: false, //默认是true，如果需要频繁获取地理位置，请设置false
        onSuccess: function (result) {
          /* 高德坐标 result 结构
          {
              longitude : Number,
              latitude : Number,
              accuracy : Number,
              address : String,
              province : String,
              city : String,
              district : String,
              road : String,
              netType : String,
              operatorType : String,
              errorMessage : String,
              errorCode : Number,
              isWifiEnabled : Boolean,
              isGpsEnabled : Boolean,
              isFromMock : Boolean,
              provider : wifi|lbs|gps,
              isMobileEnabled : Boolean
          }
          */
          console.log(result)
          resolve(result)
        },
        onFail: function (err) {
          console.log('error: ' + JSON.stringify(err))
        }
      });
    })
  }
  
  //持续定位获取经纬度
  static async getGeolocationStart() {
    return new Promise(async (resolve, reject) => {
      await DingTalk.ready()
      dd.device.geolocation.start({
        targetAccuracy: 200, // 期望精确度
        iOSDistanceFilter: 200, // 变更感知精度(iOS端参数)
        useCache: false, // 是否使用缓存(Android端参数)
        withReGeocode: true, // 是否返回逆地理信息,默认否
        callBackInterval: 5000, //回传时间间隔，ms
        sceneId: Math.random() * 10000, // 定位场景id,
        onSuccess: function (result) {
          /*  结果同dd.device.geolocation.get */
          resolve(result)
        },
        onFail: function (err) {
          console.log('error: ' + JSON.stringify(err))
        }
      });
    })
  }
}